<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2019/7/17
 * Time: 10:43
 */

namespace app\api\controller\v12;


use app\api\controller\v2\Auth;
use app\common\cachemodel\Rectification as RectificationCacheModel;
use app\common\model\Rectification as RectificationModel;
use Exception;
use think\Log;

/**
 * 校准生辰（时间以字符串的格式传递给服务器）
 * Class Rectification
 * @package app\api\controller\v8
 */
class Rectification extends Auth
{
    /**
     * 接口，校准生辰列表
     * @title
     * @method GET
     * @desc /rectifications
     * @params type 1=》校准生辰结果列表  ，2=》草稿记录
     * @readme /doc/md/rectification/index.md
     * @throws Exception
     */
    public function index()
    {
        $recs = (new RectificationCacheModel())->RectificationList($this->user['id']);
        $data = [];
        foreach ($recs['data'] as $rec)
        {
            $data[] = [
                'create_time' => date('Y-m-d H:i:s', $rec['create_time']),
                'status' => (int)$rec['status'],
                'title' => '校正信息（东八区时间）',
                'des1' => '出生时间：' . date('Y-m-d', $rec['start_time']),
                'des2' => '时间范围：' . date('H:i', $rec['start_time']) . '-' . ((date('d', $rec['start_time']) != date('d', $rec['end_time'])) ? '次日' : '') . date('H:i', $rec['end_time']),
                'reid' => (int)$rec['id']
            ];
        }
        $recs['data'] = $data;
        return show(config('code.success'), '获取成功', $recs);
    }

    /**
     * 校准生辰详情
     * @throws Exception
     */
    public function read()
    {
        $param['reid'] = input('reid/d', 0);
        if (!$param['reid'])
        {
            Log::write('请求参数异常：' . json_encode($this->request->param(), JSON_UNESCAPED_UNICODE), 'error', true);
            return show(config('code.error'), '未知的数据');
        }
        //获取校准生辰数据
        $rec = current((new RectificationCacheModel())->getRecDetail($param['reid']));
        if ($rec && $rec['uid'] == $this->user['id'])
        {
            $arr = [
                'recode_time' => date('Y-m-d', $rec['start_time']),
                'start_time' => date('H:i', $rec['start_time']),
                'end_time' => ((date('d', $rec['start_time']) != date('d', $rec['end_time'])) ? '次日' : '') . date('H:i', $rec['end_time']),
                'events' => $rec['events'],
                'result' => $rec['result']
            ];
            return show(config('code.success'), '获取成功', $arr);
        }
        return show(config('code.error'), '当前数据不存在');
    }

    /**
     * 开始矫正
     * @return \think\response\Json
     * @throws Exception
     */
    public function start()
    {
        if (!request()->isPost())
        {
            return show(config('code.error'), '未知操作', '', 403);
        }
        // 检测是否支付了
        $reid = input('reid/d');// 校准生辰id

        if (!$reid)
        {
            return show(config('code.error'), '参数错误');
        }

        try
        {
            $RectificationCacheModel = new RectificationCacheModel();
            //获取校准生辰数据
            $rec = current($RectificationCacheModel->getRecDetail($reid));
            if (!$rec || $rec['uid'] != $this->user['id'])
            {
                return show(config('code.error'), '数据不存在');
            }
            $event_array = [];
            foreach ($rec['events'] as $event)
            {
                $event['time'] = strtotime($event['time']);
                $event_array[] = $event;
            }
            $recode = (new \app\common\cachemodel\Recode())->getInfoById($rec['rid']);
            $RectificationCacheModel->saveRec($this->user['id'], $reid, ['status' => 1], $event_array);
            $orders = RectificationModel::hasWhere('Orders', ['is_del' => 0, 'reid' => $reid])->field('order_id,trade_type,pay_time,return_time,total_amount')->find();
            (new \app\common\cachemodel\Orders())->UpdateData($orders->order_id, ['status' => 1], 1);

            if ($orders && $orders->status)
            {
                $data = [
                    'oid' => (int)$orders->id,
                    'order_id' => $orders->order_id,
                    'reid' => (int)$reid,
                    'start_time' => $rec['start_time'],
                    'end_time' => $rec['end_time'],
                    'events' => $event_array,
                    'recode' => $recode
                ];
                $queueConfig = config('queue');
                queuePush($queueConfig['rectification_task'], $data, $queueConfig['rectification_queue'], $queueConfig['rectification_delay']);
            }
        }
        catch (\Exception $e)
        {
            return show(config('code.error'), '当前数据无订单');
        }

        return show(config('code.success'), '开始校正，等待校正结果', ['order_id' => $orders->order_id]);
    }
}
